import {
  Cartesian3,
  Color,
  EllipsoidSurfaceAppearance,
  GeometryInstance,
  GroundPrimitive,
  Material,
  PolygonGeometry,
  PolygonHierarchy,
  PrimitiveCollection,
  Resource,
} from '@space8/czm-plugin';

export function addWaterLayer(primitiveCollection: PrimitiveCollection, url: string) {
  // 添加河道
  const geometryInstances: any[] = [];
  Resource.fetchJson({ url: url })!.then((response) => {
    response.features.forEach((feature: any) => {
      const data = feature.geometry.coordinates;
      const polygonHierarchy = new PolygonHierarchy();
      for (let i = 0; i < data.length; i++) {
        if (i == 0) {
          polygonHierarchy.positions = data[0].map((t) => Cartesian3.fromDegrees(t[0], t[1]));
        } else {
          const holesHierarchy = new PolygonHierarchy();
          holesHierarchy.positions = data[i].map((t) => Cartesian3.fromDegrees(t[0], t[1]));
          polygonHierarchy.holes.push(holesHierarchy);
        }
      }
      const geometryInstance = new GeometryInstance({
        geometry: new PolygonGeometry({
          polygonHierarchy: polygonHierarchy,
        }),
      });
      geometryInstances.push(geometryInstance);
    });
    const primitive = new GroundPrimitive({
      allowPicking: false,
      geometryInstances: geometryInstances,
      appearance: new EllipsoidSurfaceAppearance({
        material: new Material({
          fabric: {
            type: 'Water',
            uniforms: {
              baseWaterColor: Color.fromCssColorString('#2b94ca'),
              normalMap: 'texture/waterNormals.jpg',
              frequency: 1000.0,
              animationSpeed: 0.05,
              amplitude: 5.0,
            },
          },
        }),
        fragmentShaderSource: `
          varying vec3 v_positionMC;
          varying vec3 v_positionEC;
          varying vec2 v_st;

          void main(){
            czm_materialInput materialInput;
            vec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));
            #ifdef FACE_FORWARD
            normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
            #endif
            materialInput.s = v_st.s;
            materialInput.st = v_st;
            materialInput.str = vec3(v_st, 0.0);
            materialInput.normalEC = normalEC;
            materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);
            vec3 positionToEyeEC = -v_positionEC;
            materialInput.positionToEyeEC = positionToEyeEC;
            czm_material material = czm_getMaterial(materialInput);
            #ifdef FLAT
            gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);
            #else
            gl_FragColor = czm_phong(normalize(positionToEyeEC), material);
            gl_FragColor.a=0.85;
            #endif
          }
        `,
      }),
    });
    primitiveCollection.add(primitive);
  });
}
